package com.google.code.p.narcissus.core.remote;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import org.apache.log4j.Logger;

public class RemoteRobot extends UnicastRemoteObject implements IRemoteRobot {

	private static final Logger LOGGER = Logger.getLogger(RemoteRobot.class.getName());

	protected RemoteRobot(int port) throws RemoteException {
		super(port);
	}

	private static final long serialVersionUID = 1L;

	@Override
	public SerializableImage createScreenCapture(Rectangle snapRect) throws RemoteException {
		LOGGER.info("Taking Screenshot of dimension: " + snapRect.toString());
		Robot robot;
		try {
			robot = new Robot();
			robot.mouseMove(0, 0);
			return new SerializableImage(robot.createScreenCapture(snapRect));
		} catch (AWTException e) {
			throw new RemoteException("Impossible to get a hold of the graphical context", e);
		} catch (IOException e) {
			throw new RemoteException("Impossible to write image taken in serializable format", e);
		}
	}

	@Override
	public void mouseMove(int x, int y) throws RemoteException {
		try {
			new Robot().mouseMove(x, y);

		} catch (AWTException e) {
			throw new RemoteException("Impossible to get a hold of the graphical context", e);
		}
	}

	@Override
	public Dimension getScreenSize() throws RemoteException {
		return Toolkit.getDefaultToolkit().getScreenSize();
	}
}